operations = ['dropoff', 'pickup', 'collect', 'delivery']

fields_map = {
    'operation_dropoff': 'dropoff',
    'operation_pickup': 'pickup',
    'operation_collect': 'collect',
    'operation_delivery': 'delivery'
}


class OperationControlFC(object):
    """
    Model:
        头尾程并入增值服务后的操作控制

    Param:
        - env: odoo env
        - dropoff: 网点收件
        - pickup: 上门取件
        - collect: 网点取件
        - delivery: 送货上门

    Function:
        - fulfill_display: 拼接展示字符串
        - get_operation_map: 获取头尾程在增值服务表中的映射关系
        - update_value_add_list: 更新增值服务IDS
        - monitor_value_add_list: 监听增资服务IDS
    """

    def __init__(self, env, dropoff=False, pickup=False, collect=False, delivery=False):
        self.env = env
        self.operation_dropoff = dropoff
        self.operation_pickup = pickup
        self.operation_collect = collect
        self.operation_delivery = delivery

    def fulfill_display(self):
        """ 拼接展示字符串 """
        char1 = '√' if self.operation_dropoff else '-'
        char2 = '√' if self.operation_pickup else '-'
        char3 = '√' if self.operation_collect else '-'
        char4 = '√' if self.operation_delivery else '-'

        return '{},{},{},{}'.format(char1, char2, char3, char4)

    def get_operation_map(self):
        """ 获取头尾程在增值服务表中的映射关系 """
        services = self.env['rp.value.added.service'].search([('name', 'in', operations)])
        service_ids = {service.name: service.id for service in services}
        return service_ids

    def get_current_ids(self):
        """ 获取当前已激活的头尾程的IDS """

        operation_map = self.get_operation_map()

        current_ids = []

        for k, v in fields_map.items():
            service_id = operation_map.get(v)
            if getattr(self, k):
                current_ids.append(service_id)

        return current_ids

    def update_value_add_list(self, value_add_list):
        """ 更新增值服务IDS """
        operation_map = self.get_operation_map()

        for k, v in fields_map.items():
            service_id = operation_map.get(v)
            if getattr(self, k):
                value_add_list.append(service_id)
            else:
                value_add_list = [x for x in value_add_list if x != service_id]

        return list(set(value_add_list))

    def monitor_value_add_list(self, value_add_list):
        """ 监听增资服务IDS，头尾程的IDS不允许丢掉 """
        current_ids = self.get_current_ids()

        value_add_set = set(value_add_list)
        current_ids_set = set(current_ids)

        return current_ids_set.issubset(value_add_set)
